const mysql = require('mysql')
const {config} = require('../config/index')

function connect () { 
  const { host, user, password, database, port } = config;
  return mysql.createConnection({ 
    host,
    user,
    password,
    database,
    port
  })
}

//新建查询连接
function querySql (sql) {
  const conn = connect();
  return new Promise((resolve, reject) => {
    try {
      conn.query(sql, (err, res) => {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      })
    } catch (e) {
      reject(e);
    } finally {
      //释放连接
      conn.end();
    }
  })
}

//查询一条语句
function queryOne (sql) {
  return new Promise((resolve, reject) => {
    querySql(sql).then(res => {
      if (res && res.length > 0) {
        resolve(res[0]);
      } else {
        resolve(null);
      }
    }).catch(err => {
      reject(err);
    })
  })
}
//格式化输出数据
function format(data,type){
    if(type=='Array'){
        let result = {
            list:data
        }
        return result
    }else if(type == 'Object'){
        return data[0]==null?null:data[0]
    }else if(type == 'Normal'){
      return data
    }
}
//封装返回的数据
function formatJson(data1,type){
   let data = (data1 == undefined?null:data1)
    let result 
    if (!data) {
        result = {
            code: 500,
            data: format(data,type)
    }
    }else{
        result = {
            code: 200,
            data: format(data,type)
    }
    } 
    
    return result
}
module.exports = {
  querySql,
  queryOne,
  formatJson
}